﻿/*
 * ========================================================================
 * Copyright(c) 2007-2012 情留メ蚊子, All Rights Reserved.
 * Welcom use the LiteFetion.
 * See more information,Please goto http://www.94qing.com
 * ========================================================================
 * 
 * 作 者：情留メ蚊子
 * Q  Q: 540644769
 * 邮 箱：qlwz@qq.com
 * 网 址：http://www.94qing.com
 * ========================================================================
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using LiteFetion.Model;
using LiteFetion.Notify;

namespace LiteFetion
{
    public class FetionClient
    {
        public FetionClient()
        {
            this.User = new User();
            this.LoginManager = new LoginManager(this);
            this.BuddyManager = new BuddyManager(this);
            this.MessageManager = new MessageManager(this);
            this.UserManager = new UserManager(this);
            this.BuddyList = new List<Buddy>();
            this.CordList = new List<Cord>();
        }

        /// <summary>
        /// 请求的版本,每请求一次递增
        /// </summary>
        public int RequestVersion { get; set; }

        /// <summary>
        /// 获取Notify的失败次数
        /// </summary>
        public int PollNotifyFailed { get; set; }

        /// <summary>
        /// 用户信息
        /// </summary>
        public User User { get; private set; }

        /// <summary>
        /// 好友列表
        /// </summary>
        public List<Buddy> BuddyList { get; set; }

        /// <summary>
        /// 分组列表
        /// </summary>
        public List<Cord> CordList { get; set; }

        /// <summary>
        /// 日志管理
        /// </summary>
        public LogManager LogManager { get; set; }

        /// <summary>
        /// 登录管理
        /// </summary>
        public LoginManager LoginManager { get; private set; }

        /// <summary>
        /// 好友管理
        /// </summary>
        public BuddyManager BuddyManager { get; private set; }

        /// <summary>
        /// 消息管理
        /// </summary>
        public MessageManager MessageManager { get; private set; }

        /// <summary>
        /// 用户管理
        /// </summary>
        public UserManager UserManager { get; private set; }

        /// <summary>
        /// 客户端状态
        /// </summary>
        public ClientState ClientState { get; private set; }

        /// <summary>
        /// 循环线程
        /// </summary>
        public Thread Thread { get; private set; }

        /// <summary>
        /// 登录，会进行一些的操作，页面登录，获取个人信息，获取好友列表，获取好友状态等。。
        /// </summary>
        /// <param name="account">用户名，可以是手机号，飞信号，注册的邮件</param>
        /// <param name="password">密码</param>
        /// <param name="state">登录状态</param>
        /// <param name="verifyImage">验证码，登录的过程需要验证码</param>
        /// <returns></returns>
        public ActionResult Login(string account, string password, BuddyState state, VerifyImage verifyImage)
        {
            this.PollNotifyFailed = 0;
            this.ClientState = ClientState.LOGGING;
            User.Account = account;
            User.Password = password;
            this.LogManager = new LogManager(this);
            //第一步登录
            ActionResult result = this.LoginManager.Login(account, password, state, verifyImage);
            if (result != ActionResult.SUCCESS)
            {
                this.ClientState = ClientState.LOGIN_FAIL;
                return result;
            }

            //第二步获取个人信息
            result = this.LoginManager.GetPersonalInfo();
            if (result != ActionResult.SUCCESS)
            {
                this.ClientState = ClientState.LOGIN_FAIL;
                return result;
            }

            //第三步获取好友列表
            result = this.LoginManager.GetBuddyList();
            if (result != ActionResult.SUCCESS)
            {
                this.ClientState = ClientState.LOGIN_FAIL;
                return result;
            }

            //获取好友信息
            new NotifyManager(this).PollNotify();

            this.ClientState = ClientState.ONLINE;
            Thread = new Thread(new ThreadStart(ListenThreadRun));
            Thread.Start();
            return result;
        }

        /// <summary>
        /// 退出登录，完成主页面退出请求
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            ActionResult result = this.LoginManager.Logout();
            //if (result == ActionResult.SUCCESS)
            //{
            this.ClientState = ClientState.LOGOUT;
            if (this.Thread != null) Thread.Abort();
            //}
            return result;
        }

        public void ListenThreadRun()
        {
            NotifyManager notify = new NotifyManager(this);
            ActionResult result = ActionResult.SUCCESS;
            while (true)
            {
                if (this.ClientState == ClientState.ONLINE)
                {
                    result = notify.PollNotify();
                    if (result != ActionResult.SUCCESS)
                    {
                        new ClientStateNotify(this, ClientState.NET_ERROR);
                        this.ClientState = ClientState.NET_ERROR;
                        Logout();
                        break;
                    }
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }

        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <param name="type">验证码类型，也就是验证图片的SessionId， 定义在VerifyImage.TYPE_*</param>
        /// <returns>验证码，如果失败返回null</returns>
        public VerifyImage GetVerifyImage(string type)
        {
            string picurl = string.Format(Gobal.WEBIM_URL_GET_PIC, type);
            HttpHelper http = new HttpHelper();
            http.Url = picurl;
            http.PostData = "c:\\1.jpg";
            byte[] data = http.GetStream();
            Cookie cookie = http.Cookies.Find(p => p.Name.Compare(type));
            if (cookie == null)
            {
                return null;
            }
            VerifyImage image = new VerifyImage();
            image.VerifyType = type;
            image.ImageData = data;
            image.SessionId = cookie.Value;
            return image;
        }

        public void Debug(HttpHelper http)
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine(string.Format("\r\n==========QQ:{1}, {0} ==========", DateTime.Now.ToString(), User.Account));
            str.AppendLine("Address : " + http.Url);
            str.AppendLine("PostData : " + http.PostData);
            str.AppendLine("StatusCode : " + http.StatusCode);
            if (!http.ErrMsg.IsEmpty())
            {
                str.AppendLine("ErrMsg : " + http.ErrMsg);
            }
            try
            {
                str.AppendLine("Json : ");
                str.AppendLine(Newtonsoft.Json.Linq.JObject.Parse(http.Html).ToString());
            }
            catch
            {
                str.AppendLine("Html : " + http.Html);
            }
            str.AppendLine("=====================");
            this.LogManager.Log(str.ToString());
        }
    }
}
